home *** CD-ROM | disk | FTP | other *** search
- Path: newsfeed.direct.ca!usenet
- From: ken@direct.ca (Ken Clark)
- Newsgroups: comp.lang.c++
- Subject: Smart Pointer Implementation & question
- Date: 16 Jan 1996 05:46:14 GMT
- Organization: Internet Direct
- Message-ID: <4dfe36$d99@grid.direct.ca>
- NNTP-Posting-Host: 204.174.244.2
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.6
-
- Hi. I have implemented a reference counting smart pointer class. It works
- well, except that I can't get a basic behavior of normal pointers: automatic
- casting of subclass pointers. Consider class shape and subclass circle. I
- can do
- shape *s;
- circle *c;
- ...
- s = c;
-
- What I want to be able to do (with the same semantics)
- RCPtr<shape> s;
- RCPtr<circle> c;
- ...
- s = c;
-
- I think I understand why I can't do this (Stoustrup's square peg in round hole
- analogy). My question is, how do I get this behavior if that is what I want?
-
-
- I have included the class below. Any other suggestions on how to improve it
- are appreciated. Feel free to use the class in your code if you like.
-
- Thanks,
-
- - Ken
-
-
- template <class T>
- class RCPtr {
- struct RCPtrRep {
- T *p;
- unsigned count;
- RCPtrRep(T* ip = 0) { p = ip; count = 1; }
- ~RCPtrRep() { delete p; }
- } *rep;
- public:
- RCPtr(T *ip = 0) { rep = new RCPtrRep(ip); }
- RCPtr& operator=(T *ip)
- {
- RCPtr::~RCPtr();
- rep = new RCPtrRep(ip);
- return *this;
- }
- RCPtr& operator=(const RCPtr& rip)
- {
- rip.rep->count++;
- RCPtr::~RCPtr();
- rep = rip.rep;
- return *this;
- }
- ~RCPtr()
- {
- if (--rep->count == 0) delete rep;
- }
- T *operator->() { return (T *)rep->p; }
- T& operator*() { return *(T *)rep->p; }
- };
-
-
-